/*
 * @Author: HuangYue
 * @Date: 2022-04-12 15:29:54
 * @LastEditors: HuangYue
 * @LastEditTime: 2022-04-28 00:57:12
 * @FilePath: /graduation/src/pages/Admin/HospitalManagement/index.jsx
 * @Description:admin 医院管理界面
 */
import { Popconfirm, message, Drawer, Button } from 'antd';
import React, { useState } from 'react';
import { useModel } from 'umi';
import ProTable from '@ant-design/pro-table';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormDateRangePicker,
} from '@ant-design/pro-form';
import { FormattedMessage } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProDescriptions from '@ant-design/pro-descriptions';
import { PlusOutlined } from '@ant-design/icons';
import {
  getAllHospital,
  addHospital,
  updateHospital,
  deleteHospital,
} from '@/services/mockApi/hospitalManage';
import { randomID } from '../../../../src/util/random';
import moment from 'moment';

const HospitalManagement = () => {
  const [allHospitalDataSource, setAllHospitalDataSource] = useState([]);
  const [showDetail, setShowDetail] = useState(false); // 详情界面
  const [createModalVisible, setModalVisible] = useState(false); // 编辑 + 新增界面
  const [currentRow, setCurrentRow] = useState(undefined); // 当前操作行
  const [startTime, setStartTime] = useState(null); // 开始时间
  const [endTime, setEndTime] = useState(null); // 结束时间
  //获取当前用户信息
  const { initialState, serInitialState } = useModel('@@initialState');
  const { currentUser } = initialState;
  /**
   *  Delete node
   * @zh-CN 删除人员
   *
   * @param selectedRows
   */

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      hide();
      const { uid } = selectedRows;
      const res = await deleteHospital(uid);
      if (res.success) {
        setAllHospitalDataSource(res.data);
        setCurrentRow(false);

        message.success('Deleted successfully and will refresh soon');
      }
      return true;
    } catch (error) {
      hide();
      message.error('Delete failed, please try again');
      return false;
    }
  };
  const columnsForTable = [
    {
      dataIndex: 'hospitalName',
      title: '医院名字',
      align: 'center',
      width: 400,
      rowKey: 1,
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            {record.hospitalNames}
          </a>
        );
      },
    },
    {
      dataIndex: 'address',
      rowKey: 2,
      align: 'center',
      width: 300,
      title: '地址',
    },
    {
      dataIndex: 'responsiblePerson',
      align: 'center',
      rowKey: 3,
      width: 150,
      title: '医院负责人',
      render: (_, record) => {
        return <span>{record.responsiblePerson.name}</span>;
      },
    },
    {
      dataIndex: 'responsiblePersonPhone',
      width: 150,
      rowKey: 4,
      align: 'center',
      title: '联系方式',
      render: (_, record) => <span>{record.responsiblePerson.phone}</span>,
    },

    {
      dataIndex: 'personNumber',
      title: '数量统计',
      rowKey: 5,
      align: 'center',
      width: 600,
      children: [
        {
          dataIndex: 'bypassAccountNumber',
          rowKey: 'bypassAccountNumber',
          title: '子账号数量',
          align: 'center',
          width: 200,
          render: (_, record) => {
            return <span>{record.bypassAccountList.length}</span>;
          },
        },
        {
          dataIndex: 'engineerNumber',
          rowKey: 'engineerNumber',
          align: 'center',
          width: 200,
          title: '入驻工程师',
          render: (_, record) => {
            return <span>{record.engineerList.length}</span>;
          },
        },
        {
          dataIndex: 'deviceListNumber',
          rowKey: 'deviceListNumber',
          align: 'center',
          width: 200,
          title: '账号数量',
          render: (_, record) => {
            return <span>{record.deviceList.length}</span>;
          },
        },
      ],
    },
    {
      dataIndex: 'createdAt',
      rowKey: 'createdAt',
      title: '创建时间',
      width: 200,
      valueType: 'date',
    },
    {
      dataIndex: 'status',
      rowKey: 'status',
      title: '状态',
      width: 150,
      align: 'center',
      filters: true,
      onFilter: true,
      search: false,
      valueEnum: {
        Expire: { text: '过期', status: 'Default' },
        Approving: { text: '审核中', status: 'Processing' },
        Success: { text: '正常', status: 'Success' },
        DueSoon: { text: '即将过期', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'x',
      rowKey: 'x',
      width: 200,
      valueType: 'option',
      fixed: 'right',
      search: false,
      render: (_, record) => {
        return [
          <a
            key="edit"
            onClick={() => {
              const { contractTime } = record;
              setStartTime(contractTime[0]);
              setEndTime(contractTime[1]);
              setCurrentRow(record);
              setShowDetail(false);
              setModalVisible(true);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="confirm"
            title={`确认删除吗?`}
            okText="是"
            cancelText="否"
            onConfirm={async () => {
              await handleRemove(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];
  return (
    <PageContainer
      header={{
        title: '医院管理',
        ghost: true,
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '管理页',
            },
            {
              path: '/admin/peopleManagement',
              breadcrumbName: '医院管理页面',
            },
          ],
        },
      }}
    >
      <ProTable
        columns={columnsForTable}
        request={async (params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          // console.log(params, sorter, filter);
          const res = await getAllHospital();
          return {
            success: true,
            data: res.data,
            total: res.total,
          };
        }}
        params={allHospitalDataSource}
        polling={2000}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setModalVisible(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        rowKey="uid"
        pagination={{
          showQuickJumper: true,
        }}
        search={true}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
          setModalVisible(false);
        }}
        closable={false}
      >
        {currentRow?.uid && (
          <ProDescriptions
            column={2}
            title={`${currentRow.hospitalNames + ' ' + currentRow.uid}`}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.uid,
            }}
          >
            <ProDescriptions.Item span={2} dataIndex="hospitalNames" label="医院名字" />
            <ProDescriptions.Item span={2} dataIndex="address" label="医院地址" />
            <ProDescriptions.Item
              dataIndex="responsiblePersonName"
              label="医院负责人"
              render={(_, record) => <span>{record.responsiblePerson.name}</span>}
            />
            <ProDescriptions.Item
              dataIndex="responsiblePersonPhone"
              label="医院联系方式"
              render={(_, record) => <span>{record.responsiblePerson.phone}</span>}
            />
            <ProDescriptions.Item dataIndex="uid" label="合同编号" />
            <ProDescriptions.Item dataIndex="mangerName" label="合同处理人" />
            <ProDescriptions.Item dataIndex="createTime" label="合同创建时间" valueType="date" />
            <ProDescriptions.Item
              dataIndex="contractTime"
              label="合同有效期"
              render={(item) => {
                return <span>{`${moment(item[1]).diff(item[0], 'day') + 1}天`}</span>;
              }}
            />
            <ProDescriptions.Item
              dataIndex="useMode"
              label="合同生效方式"
              valueEnum={{
                chapter: { text: '盖章后生效' },
              }}
            />
            <ProDescriptions.Item
              dataIndex="unusedMode"
              label="合同失效方式"
              valueEnum={{
                time: { text: '履行完终止' },
              }}
            />

            <ProDescriptions.Item
              dataIndex="status"
              label="账号状态"
              valueEnum={{
                Expire: { text: '过期', status: 'Default' },
                Approving: { text: '审核中', status: 'Processing' },
                Success: { text: '正常', status: 'Success' },
                DueSoon: { text: '即将过期', status: 'Error' },
              }}
            />
          </ProDescriptions>
        )}
      </Drawer>
      <ModalForm
        title="添加合同"
        initialValues={{
          ...currentRow,
          uid: currentRow?.uid || randomID(),
          responsiblePersonName: currentRow?.responsiblePerson?.name,
          responsiblePersonPhone: currentRow?.responsiblePerson?.phone,
          mangerName: currentRow?.mangerName || currentUser.realName,
        }}
        visible={createModalVisible}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setCurrentRow(null);
            setStartTime(null);
            setEndTime(null);
          },
        }}
        onFinish={async (value) => {
          let res;
          if (currentRow) {
            res = await updateHospital(value);
          } else {
            res = await addHospital(value);
          }
          if (res.success) {
            setAllHospitalDataSource(res.data);
            message.success('提交成功,请刷新后尝试');
          } else {
            setModalVisible(false);
            setShowDetail(false);
            message.error('提交失败');
          }
          setCurrentRow(undefined);
          return true;
        }}
        onVisibleChange={setModalVisible}
      >
        <ProForm.Group>
          <ProFormText
            width="md"
            name="hospitalNames"
            label="签约客户名称"
            tooltip="最长为24位的医院名称"
            placeholder="请输入医院名称名称"
            rules={[
              {
                required: true,
                message: '请输入医院名字',
              },
            ]}
          />

          <ProFormText
            width="md"
            name="company"
            label="我方公司名称"
            placeholder="请输入名称"
            disabled={true}
            allowClear={false}
            initialValue="Telemedicine"
          />
          <ProFormText width={688} name="address" label="详细地址" />
        </ProForm.Group>

        <ProForm.Group>
          <ProFormText
            width="md"
            allowClear={false}
            disabled={true}
            name="uid"
            rules={[
              {
                required: true,
                message: '请确定合同编号',
              },
            ]}
            label="合同编号"
          />
          <ProFormText width="md" name="contract" label="合同名称" placeholder="请输入名称" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            options={[
              {
                value: 'chapter',
                label: '盖章后生效',
              },
            ]}
            width="md"
            name="useMode"
            rules={[
              {
                required: true,
                message: '请选择合同约定生效方式',
              },
            ]}
            label="合同约定生效方式"
          />
          <ProFormSelect
            width="md"
            options={[
              {
                value: 'time',
                label: '履行完终止',
              },
            ]}
            rules={[
              {
                required: true,
                message: '请选择合同约定失效方式',
              },
            ]}
            name="unusedMode"
            label="合同约定失效方式"
          />
          <ProFormDateRangePicker
            width="xl"
            onChange={(time) => {
              setStartTime(time[0]);
              setEndTime(time[1]);
            }}
            rules={[
              {
                required: true,
                message: '请选择合同生效时间',
              },
            ]}
            name="contractTime"
            label="合同生效时间"
          />
          <ProFormText
            label=" "
            allowClear
            readonly
            fieldProps={{
              value: `有效天数: ${startTime ? moment(endTime).diff(startTime, 'day') + 1 : 0} 天`,
            }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            width="md"
            rules={[
              {
                required: true,
                message: '请输入负责人姓名',
              },
            ]}
            name="responsiblePersonName"
            label="负责人"
          />
          <ProFormText
            width="md"
            rules={[
              {
                required: true,
                message: '请输入负责人联系方式',
              },
            ]}
            name="responsiblePersonPhone"
            label="负责人联系方式"
          />
        </ProForm.Group>
        <ProFormText
          width="xs"
          name="mangerName"
          disabled={true}
          allowClear={false}
          label="处理人"
        />
      </ModalForm>
    </PageContainer>
  );
};

export default HospitalManagement;
